package com.djhu.mybatis;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Properties;

/**
 * Created by zw on 2018/3/2.
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class}
), @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})public class SqlStatInterceptor implements Interceptor {
    private static Logger logger = LoggerFactory.getLogger(SqlStatInterceptor.class.getName());

    private int maxusetime = 1000;

    private SqlLogger sqlLogger;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        Object parameter = null;
        if(invocation.getArgs().length > 1) {
            parameter = invocation.getArgs()[1];
        }
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        long start = System.currentTimeMillis();
        try {
            return invocation.proceed();
        }finally {
            long used = System.currentTimeMillis() - start;
            if (used > maxusetime){
                SqlEntity sqlEntity = new SqlEntity();
                sqlEntity.setBoundsql(boundSql.getSql());
                sqlEntity.setUsedTime(used);
                sqlLogger.log(sqlEntity);
            }
            //System.out.println(boundSql.getSql());
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }


    public int getMaxusetime() {
        return maxusetime;
    }

    public void setMaxusetime(int maxusetime) {
        this.maxusetime = maxusetime;
    }

    public SqlLogger getSqlLogger() {
        return sqlLogger;
    }

    public void setSqlLogger(SqlLogger sqlLogger) {
        this.sqlLogger = sqlLogger;
    }
}